package com.lzw.bluetoothpractice.Activitys;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.Html;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewStructure;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bumptech.glide.Glide;
import com.lzw.bluetoothpractice.Adapters.DetailForumAdapter;
import com.lzw.bluetoothpractice.Adapters.RecommendDoctorListAdapter;
import com.lzw.bluetoothpractice.Adapters.RecoveryForumListAdapter;
import com.lzw.bluetoothpractice.AppConfig;
import com.lzw.bluetoothpractice.Models.Comment;
import com.lzw.bluetoothpractice.Models.Forum;
import com.lzw.bluetoothpractice.Models.Review;
import com.lzw.bluetoothpractice.Models._User;
import com.lzw.bluetoothpractice.R;
import com.lzw.bluetoothpractice.Utils.AppUtil;
import com.lzw.bluetoothpractice.Utils.SharePreferenceUtils;
import com.lzw.bluetoothpractice.bean.CommentBean;
import com.lzw.bluetoothpractice.bean.ForumBean;
import com.lzw.bluetoothpractice.bean.RecommendDoctorBean;
import com.lzw.bluetoothpractice.bean.SystemUserBean;
import com.lzw.bluetoothpractice.bean.UserBean;
import com.lzw.bluetoothpractice.network.HeadAssmblyUtils;
import com.lzw.bluetoothpractice.network.RetrofitManager;
import com.lzw.bluetoothpractice.network.api.RequestApi;

import java.util.Date;
import java.util.List;
import java.util.Map;

import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.BmobUser;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.FindListener;
import cn.bmob.v3.listener.QueryListener;
import cn.bmob.v3.listener.SaveListener;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

import static com.lzw.bluetoothpractice.MyApplication.getContext;

public class DetailForumActivity extends BaseActivity{
    ImageView head;   //头像
    TextView name;    //姓名
    TextView time;   //时间
    TextView question; //问题
    TextView reviewsum;  //回复数
    EditText reviewcontent;  //回复内容
    ImageView forum_pic;
    TextView type; //手术类型
    RecyclerView   detailrecyclerview;  //列表
    DetailForumAdapter detailForumAdapter;//适配器
    private Map<String, String> keyMap;
    String forum_id;
    String forum_userId;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_detail_forum);
        Intent intent = getIntent();
        forum_id= intent.getStringExtra("forum_id");
        forum_userId= intent.getStringExtra("forum_userId");
        InitNavBar2(true,"论坛详情",false);
        init();
        getUser(forum_userId);
        getContent(forum_id);
        getReviews(forum_id);
        //发送信息

        reviewcontent.setOnEditorActionListener(new EditText.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEND) {
                    try {
                        keyMap = HeadAssmblyUtils.HeadAssembly("/dev-api/android/forum/getInfoForAndroid");
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    String userid = SharePreferenceUtils.getString(getContext(),"userId",null);
                    String accessToken = SharePreferenceUtils.getString(getContext(),"access_token",null);;
                    Comment comment=new Comment();
                    comment.setCommentContent(v.getText().toString());
                    comment.setUserId(Long.parseLong(userid));
                    comment.setForumId(Long.parseLong(forum_id));

                    RetrofitManager.getInstance(AppConfig.BASE_URL)
                            .createReq(RequestApi.class).addComment(comment,"1", AppUtil.getVersionCode() + "", accessToken ,keyMap.get("gmtStr"), keyMap.get("contentMD5"), keyMap.get("hmacCode")).
                            observeOn(AndroidSchedulers.mainThread()).subscribeOn(Schedulers.io()).subscribe(new Subscriber<JSONObject>() {
                        @Override
                        public void onCompleted() {

                        }

                        @Override
                        public void onError(Throwable e) {

                            Log.e("登录",e.getMessage()+"");

                        }

                        @Override
                        public void onNext(JSONObject json) {

                            ForumBean forumBean = JSON.parseObject(json.toString(), ForumBean.class);
                            if(forumBean.getCode()==200){

                                reviewcontent.setText("");
                                Toast.makeText(DetailForumActivity.this,"评论成功",Toast.LENGTH_LONG).show();
                                getReviews(forum_id);

                            }else {
                                Toast toast=Toast.makeText(DetailForumActivity.this,"查询论坛详细信息失败",Toast.LENGTH_LONG);
                                toast.show();
                            }


                        }
                    });
                    return true;
                }
                return false;
            }
        });
    }
    //进行查询得到内容
    private void getContent(String forum_id) {
        try {
            keyMap = HeadAssmblyUtils.HeadAssembly("/dev-api/android/forum/getInfoForAndroid");
        } catch (Exception e) {
            e.printStackTrace();
        }
        String accessToken = SharePreferenceUtils.getString(getContext(),"access_token",null);;

        RetrofitManager.getInstance(AppConfig.BASE_URL)
                .createReq(RequestApi.class).getforum(Long.parseLong(forum_id),"1", AppUtil.getVersionCode() + "", accessToken ,keyMap.get("gmtStr"), keyMap.get("contentMD5"), keyMap.get("hmacCode")).
                observeOn(AndroidSchedulers.mainThread()).subscribeOn(Schedulers.io()).subscribe(new Subscriber<JSONObject>() {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable e) {

                Log.e("登录",e.getMessage()+"");

            }

            @Override
            public void onNext(JSONObject json) {

                ForumBean forumBean = JSON.parseObject(json.toString(), ForumBean.class);
                if(forumBean.getCode()==200){

                    question.setText(Html.fromHtml(forumBean.getData().getForumContent()));
                    time.setText(forumBean.getData().getCreateTime().toLocaleString()+"");
                    if(!forumBean.getData().getPic().isEmpty()){
                        forum_pic.setVisibility(View.VISIBLE);
                        Glide.with(DetailForumActivity.this).load(AppConfig.BASE_URL+forumBean.getData().getPic()).into(forum_pic);

                    }
                    reviewsum.setText("回答（共"+forumBean.getData().getCommentCnt()+"条）");


                }else {
                    Toast toast=Toast.makeText(DetailForumActivity.this,"查询论坛详细信息失败",Toast.LENGTH_LONG);
                    toast.show();
                }


            }
        });
    }
    //得到发布者信息
    private void getUser(String user_id){

        try {
            keyMap = HeadAssmblyUtils.HeadAssembly("/dev-api/system/user/getInfoForAndroid");
        } catch (Exception e) {
            e.printStackTrace();
        }
        String accessToken = SharePreferenceUtils.getString(getContext(),"access_token",null);;

        RetrofitManager.getInstance(AppConfig.BASE_URL)
                .createReq(RequestApi.class).getUserById(Long.parseLong(forum_userId),"1", AppUtil.getVersionCode() + "", accessToken ,keyMap.get("gmtStr"), keyMap.get("contentMD5"), keyMap.get("hmacCode")).
                observeOn(AndroidSchedulers.mainThread()).subscribeOn(Schedulers.io()).subscribe(new Subscriber<JSONObject>() {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable e) {

                Log.e("登录",e.getMessage()+"");

            }

            @Override
            public void onNext(JSONObject json) {

                UserBean userBean = JSON.parseObject(json.toString(), UserBean.class);
                if(userBean.getCode()==200){
                    Glide.with(DetailForumActivity.this).load(AppConfig.BASE_URL+userBean.getData().getAvatar()).into(head);


                    name.setText(userBean.getData().getNickName());

                }else {
                    Toast toast=Toast.makeText(DetailForumActivity.this,"查询用户信息失败",Toast.LENGTH_LONG);
                    toast.show();
                }


            }
        });

    }
    //得到该问题的评论
    private void getReviews(String forum_id){
        try {
            keyMap = HeadAssmblyUtils.HeadAssembly("/dev-api/android/comment/researchByForumId");
        } catch (Exception e) {
            e.printStackTrace();
        }
        String accessToken = SharePreferenceUtils.getString(getContext(),"access_token",null);;

        RetrofitManager.getInstance(AppConfig.BASE_URL)
                .createReq(RequestApi.class).getforumComment(Long.parseLong(forum_id),"1", AppUtil.getVersionCode() + "", accessToken ,keyMap.get("gmtStr"), keyMap.get("contentMD5"), keyMap.get("hmacCode")).
                observeOn(AndroidSchedulers.mainThread()).subscribeOn(Schedulers.io()).subscribe(new Subscriber<JSONObject>() {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable e) {

                Log.e("登录",e.getMessage()+"");

            }

            @Override
            public void onNext(JSONObject json) {

                CommentBean commentBean = JSON.parseObject(json.toString(), CommentBean.class);
                if(commentBean.getCode()==200){
                    detailrecyclerview.setLayoutManager(new LinearLayoutManager(DetailForumActivity.this));
                    detailForumAdapter = new DetailForumAdapter(DetailForumActivity.this);
                    detailForumAdapter.updateData(commentBean.getData());
                    detailrecyclerview.setAdapter(detailForumAdapter);

                }else {
                    Toast toast=Toast.makeText(DetailForumActivity.this,"查询评论信息失败",Toast.LENGTH_LONG);
                    toast.show();
                }


            }
        });

    }
    //初始化
    private void init() {
        head = (ImageView) this.findViewById(R.id.detail_forum_head);
        name = (TextView)this.findViewById(R.id.detail_forum_name);
        time = (TextView)this.findViewById(R.id.detail_forum_time);
        question = (TextView)this.findViewById(R.id.detail_forum_question);
        reviewsum = (TextView)this.findViewById(R.id.detail_forum_reviewsum);
        reviewcontent = (EditText)this.findViewById(R.id.detail_forum_review); //输入的内容
        forum_pic=findViewById(R.id.forum_pic);
        detailrecyclerview = (RecyclerView) this.findViewById(R.id.detail_forum_reviewlist);  //列表
    }

}
